package com.dlc.shop.delivery.multishop.controller;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.dlc.shop.bean.app.dto.MyOrderDto;
import com.dlc.shop.bean.enums.OfflineHandleEventType;
import com.dlc.shop.bean.enums.StockModeEnum;
import com.dlc.shop.bean.model.OfflineHandleEvent;
import com.dlc.shop.bean.model.Order;
import com.dlc.shop.bean.model.Station;
import com.dlc.shop.bean.param.OfflineHandleEventAuditParam;
import com.dlc.shop.common.annotation.SysLog;
import com.dlc.shop.common.enums.SysTypeEnum;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.common.util.PasswordUtil;
import com.dlc.shop.common.util.PrincipalUtil;
import com.dlc.shop.delivery.common.model.OrderSelfStation;
import com.dlc.shop.delivery.common.service.OrderSelfStationService;
import com.dlc.shop.security.common.bo.UidInfoBO;
import com.dlc.shop.security.common.manager.PasswordManager;
import com.dlc.shop.security.common.manager.TokenStore;
import com.dlc.shop.security.common.util.AuthUserContext;
import com.dlc.shop.security.multishop.util.SecurityUtils;
import com.dlc.shop.service.OfflineHandleEventService;
import com.dlc.shop.service.OrderService;
import com.dlc.shop.service.OrderVirtualInfoService;
import com.dlc.shop.service.StationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 自提点
 *
 * @author YXF
 * @date 2020-04-23 15:18:29
 */
@RestController
@RequestMapping("/admin/station")
@Tag(name = "商家端自提接口")
@RequiredArgsConstructor
public class StationController {

    @Value("${yami.expose.operation.auth:}")
    private Boolean permission;
    private final StationService stationService;

    private final OrderSelfStationService orderSelfStationService;

    private final OfflineHandleEventService offlineHandleEventService;

    private final OrderService orderService;

    private final OrderVirtualInfoService orderVirtualInfoService;

    private final PasswordEncoder passwordEncoder;

    private final TokenStore tokenStore;

    private final PasswordManager passwordManager;


    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('admin:station:page')")
    @Operation(summary = "分页查询自提点信息")
    public ServerResponseEntity<IPage<Station>> getStatonPage(PageParam<Station> page, Station station) {
        station.setShopId(SecurityUtils.getShopUser().getShopId());
        return ServerResponseEntity.success(stationService.getPage(page, station));
    }

    @GetMapping("/info/{stationId}")
    @Operation(summary = "通过id查询自提点")
    @Parameter(name = "stationId", description = "自提点id" , required = true)
    @PreAuthorize("@pms.hasPermission('admin:station:info')")
    public ServerResponseEntity<Station> getById(@PathVariable("stationId") Long stationId) {
        Station station = stationService.getStationInfoById(stationId);
        if (!Objects.equals(SecurityUtils.getShopUser().getShopId(), station.getShopId())) {
            throw new YamiShopBindException("yami.no.auth");
        }
        if (StrUtil.isNotBlank(station.getPhone()) && PrincipalUtil.isMobile(station.getPhone())) {
            station.setPhone(PhoneUtil.hideBetween(station.getPhone()).toString());
        }
        return ServerResponseEntity.success(station);
    }

    @PostMapping
    @PreAuthorize("@pms.hasPermission('admin:station:save')")
    @Operation(summary = "新增自提点")
    public ServerResponseEntity<Boolean> save(@RequestBody @Valid Station station) {
        station.setShopId(SecurityUtils.getShopUser().getShopId());
        station.setAccount(null);
        station.setPassword(null);
        stationService.insertStation(station);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @PreAuthorize("@pms.hasPermission('admin:station:update')")
    @Operation(summary = "修改自提点")
    public ServerResponseEntity<Boolean> updateById(@RequestBody @Valid Station station) {
        station.setAccount(null);
        station.setPassword(null);
        Long shopId = SecurityUtils.getShopUser().getShopId();
        station.setShopId(shopId);
        stationService.updateStation(station);
        return ServerResponseEntity.success();
    }

    @SysLog("删除自提点")
    @DeleteMapping("/{stationId}")
    @Operation(summary = "通过id删除自提点")
    @Parameter(name = "stationId", description = "自提点id" , required = true)
    @PreAuthorize("@pms.hasPermission('admin:station:delete')")
    public ServerResponseEntity<Boolean> removeById(@PathVariable Long stationId) {
        Station stationDb = stationService.getStationInfoById(stationId);
        if (!Objects.equals(stationDb.getShopId(), AuthUserContext.getShopId())) {
            throw new YamiShopBindException("当前自提点不属于你的店铺");
        }
        stationService.logicDeleteById(stationId);
        tokenStore.deleteTokenByUidInfo(new UidInfoBO(SysTypeEnum.STATION, stationId.toString(), AuthUserContext.getShopId(), 0));
        return ServerResponseEntity.success();
    }

    @PutMapping("/changeAccountInfo")
    @PreAuthorize("@pms.hasPermission('admin:station:changeAccountInfo')")
    @Operation(summary = "账号密码设置")
    public ServerResponseEntity<Void> changeAccountInfo(@RequestBody @Valid Station station) {
        //staionId为83，shopId为1的门店为系统线上的数据，此判断可删除
        long stationId = 83L;
        long shopId = 1L;
        if(Objects.equals(station.getStationId(), stationId) && Objects.equals(station.getShopId(), shopId) && BooleanUtil.isFalse(permission)){
            // 没有权限进行操作
            throw new YamiShopBindException("yami.no.auth");
        }
        String decryptPassword = passwordManager.decryptPassword(station.getPassword());
        PasswordUtil.check(decryptPassword);
        station.setPassword(passwordEncoder.encode(decryptPassword));
        stationService.changeAccountInfo(station);
        tokenStore.deleteTokenByUidInfo(new UidInfoBO(SysTypeEnum.STATION, station.getStationId().toString(), AuthUserContext.getShopId(), 0));
        return ServerResponseEntity.success();
    }

    @GetMapping("/checkStationAccount")
    @Operation(summary = "校验账号")
    @Parameters({
            @Parameter(name = "stationId", description = "自提点id" ),
            @Parameter(name = "account", description = "自提点账号" )
    })
    @PreAuthorize("@pms.hasPermission('admin:station:checkAccount')")
    public ServerResponseEntity<Boolean> checkStationAccount(@RequestParam("stationId") Long stationId, @RequestParam("account") String account) {
        int count = stationService.getCountByAccount(account, stationId);
        if (count > 0) {
            return ServerResponseEntity.success(false);
        }
        return ServerResponseEntity.success(true);
    }

    @GetMapping("/getOfflineHandleEventByStatonId/{stationId}")
    @Operation(summary = "通过自提点id获取下线信息")
    @Parameter(name = "stationId", description = "自提点id" , required = true)
    @PreAuthorize("@pms.hasPermission('admin:station:offlineInfo')")
    public ServerResponseEntity<OfflineHandleEvent> getOfflineHandleEventByStatonId(@PathVariable("stationId") Long stationId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.STATION.getValue(), stationId);
        return ServerResponseEntity.success(offlineHandleEvent);
    }

    @PostMapping("/auditApply")
    @Operation(summary = "下线自提点提交审核")
    @PreAuthorize("@pms.hasPermission('admin:station:auditApply')")
    public ServerResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Station station = stationService.getById(offlineHandleEventAuditParam.getHandleId());
        if (station == null) {
            // 未找到该自提点信息
            throw new YamiShopBindException("yami.station.no.find");
        }
        stationService.auditApply(offlineHandleEventAuditParam.getEventId(), offlineHandleEventAuditParam.getHandleId(), offlineHandleEventAuditParam.getReapplyReason());
        return ServerResponseEntity.success();
    }

    @GetMapping("/getOrderItemAndStationInfo")
    @Operation(summary = "获取提货订单详情")
    @PreAuthorize("@pms.hasPermission('admin:station:orderInfo')")
    public ServerResponseEntity<OrderSelfStation> getOrderItemAndStationInfo(@RequestParam("orderNumber") String orderNumber) {
        Order order = orderService.getOrderAndOrderItemByOrderNumber(orderNumber);
        OrderSelfStation orderSelfStation = orderSelfStationService.getOne(new LambdaQueryWrapper<OrderSelfStation>().eq(OrderSelfStation::getOrderNumber, orderNumber));
        orderService.getOrderItemRefundStatus(order);
        orderSelfStation.setOrderItems(order.getOrderItems());
        return ServerResponseEntity.success(orderSelfStation);
    }

    @PutMapping("/changeStatusAndOrderStation")
    @Operation(summary = "自提订单发货")
    @PreAuthorize("@pms.hasPermission('admin:station:orderItemsDelivery')")
    public ServerResponseEntity<Void> changeStatusAndOrderStation(@RequestBody OrderSelfStation orderSelfStation) {
        List<String> orderNumberList = Lists.newArrayList();
        orderNumberList.add(orderSelfStation.getOrderNumber());
        orderService.orderStationByOrderNumber(orderNumberList, null, orderSelfStation.getStationId());
        return ServerResponseEntity.success();
    }

    @PutMapping("/changeStationOrderStatus")
    @Operation(summary = "根据自提码发货自提订单")
    @PreAuthorize("@pms.hasPermission('admin:station:orderItemsDelivery')")
    public ServerResponseEntity<Void> changeStationOrderStatus(@RequestBody OrderSelfStation orderSelfStation) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        MyOrderDto orderByStationCode = orderSelfStationService.getOrderByStationCode(orderSelfStation.getStationId(), shopId, orderSelfStation.getStationCode());
        List<String> orderNumberList = Lists.newArrayList();
        orderNumberList.add(orderByStationCode.getOrderNumber());
        orderService.orderStationByOrderNumber(orderNumberList, null, orderSelfStation.getStationId());
        return ServerResponseEntity.success();
    }

    @PutMapping("/orderWriteOffByOrderNumber")
    @Operation(summary = "用户虚拟商品订单核销操作" , description = "用户虚拟商品订单核销操作")
    @PreAuthorize("@pms.hasPermission('order:virtual:update')")
    public ServerResponseEntity<Boolean> orderWriteOffByOrderNumber(@RequestBody MyOrderDto myOrderDto) {
        String orderNumber = myOrderDto.getOrderNumber();
        Long shopId = SecurityUtils.getShopUser().getShopId();
        if (StrUtil.isBlank(orderNumber)) {
            // 订单不存在
            throw new YamiShopBindException("yami.order.no.exist");
        }
        Order orderDb = orderService.getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNumber, orderNumber)
                .eq(Order::getShopId, shopId)
                .eq(Order::getOrderMold, 1));
        if (Objects.isNull(orderDb)) {
            // 订单不存在
            throw new YamiShopBindException("yami.order.no.exist");
        }
        return ServerResponseEntity.success(orderVirtualInfoService.orderWriteOffByOrderNumber(myOrderDto, orderDb, null));
    }

    @GetMapping("/list_station")
    @Operation(summary = "获取自提点列表", description = "获取自提点列表")
    public ServerResponseEntity<List<Station>> page() {
        Long shopId = AuthUserContext.get().getShopId();
        return ServerResponseEntity.success(stationService.list(new LambdaQueryWrapper<>(Station.class)
                .eq(Station::getShopId, shopId)
                .eq(Station::getStockMode, StockModeEnum.SINGLE_STOCK.value())
                .ne(Station::getStatus, -1)));
    }

    @PutMapping("/switch_station_stock_mode")
    @Operation(summary = "切换门店库存模式", description = "切换门店库存模式")
    @Parameters({
            @Parameter(name = "stationId", description = "门店id"),
            @Parameter(name = "type", description = "更新共享库存模式（1同步到默认仓库 2库存清零）")
    })
    public ServerResponseEntity<Void> switchStationStockMode(@RequestParam("stationId") Long stationId, @RequestParam(value = "type", required = false) Integer type) {
        Long shopId = AuthUserContext.getShopId();
        Long employeeId = AuthUserContext.getEmployeeId();
        stationService.switchStationStockMode(stationId, type, shopId, employeeId);
        return ServerResponseEntity.success();
    }

}
